package com.cw.demo.utils;

import com.cw.demo.model.DbConfig;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;

public class DbXmlReadUtil {

    private Document document = null;

    public DbConfig readDbXml() throws Exception{
        DbConfig dbConfig = new DbConfig();

        //在maven工程中，可以通过一个方法，直接获取resources目录下的文件
//        InputStream resource = ClassLoader.getSystemResourceAsStream("db.xml");
        //如果是在tomcat中运行，则读取resources目录下的xml文件，需采用下面的方法调用
        InputStream resource = getClass().getClassLoader().getResourceAsStream("db.xml");


        //将给定 URI 的内容解析为一个 XML 文档,并返回Document对象

        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(resource);
        //按文档顺序返回包含在文档中且具有给定标记名称的所有 Element 的 NodeList
//        NodeList driverNameList = document.getElementsByTagName("driverName");//只有一个节点
//        String driverName = driverNameList.item(0).getTextContent();
//        System.out.println("driverName="+driverName);
//
//        NodeList urlList = document.getElementsByTagName("url");//只有一个节点
//        String url = urlList.item(0).getTextContent();
//        System.out.println("url="+url);
        String driverName = getNodeValueByNodeName("driverName");
        String url = getNodeValueByNodeName("url");
        String userName = getNodeValueByNodeName("userName");
        String password = getNodeValueByNodeName("password");
        String initialSize = getNodeValueByNodeName("initialSize");
        String minIdle = getNodeValueByNodeName("minIdle");
        String maxActive = getNodeValueByNodeName("maxActive");
        String maxWait = getNodeValueByNodeName("maxWait");
        String timeBetweenEvictionRunsMillis = getNodeValueByNodeName("timeBetweenEvictionRunsMillis");
        dbConfig.setDriverName(driverName);
        dbConfig.setUrl(url);
        dbConfig.setUserName(userName);
        dbConfig.setPassword(password);
        dbConfig.setInitialSize(Integer.parseInt(initialSize));
        dbConfig.setMinIdle(Integer.parseInt(minIdle));
        dbConfig.setMaxActive(Integer.parseInt(maxActive));
        dbConfig.setMaxWait(Integer.parseInt(maxWait));
        dbConfig.setTimeBetweenEvictionRunsMillis(Integer.parseInt(timeBetweenEvictionRunsMillis));


        return dbConfig;

    }

     private String getNodeValueByNodeName(String nodeName){
         NodeList nodeList = document.getElementsByTagName(nodeName);//只有一个节点
         String nodeValue = nodeList.item(0).getTextContent();
         return  nodeValue;
     }
}
